﻿using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.WCF.ePayment.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web.Script.Serialization;

namespace KPIS.GERP.WCF.ePayment
{
    [ServiceContract]
    public interface IAnnounceService
    {
        [OperationContract]
        string CreateAnnounceService(List<PurchaseRequestItem> PrItemList, string SiteId, string SiteCode, string SiteName, string EmpCode, string EmpName, string Tel
            , string ContactCode, string BranchName);
    }
    public class AnnounceService : IAnnounceService
    {
        public string CreateAnnounceService(List<PurchaseRequestItem> PrItemList, string SiteId, string SiteCode, string SiteName, string EmpCode, string EmpName, string Tel
            , string ContactCode, string BranchName)
        {
            ePaymentService.ServiceAPI service = new ePaymentService.ServiceAPI();
            using (var context = new ePaymentContext())
            {
                try
                {
                    var option = context.CommonOptions.ToList();
                    service.Url = option.Where(m => m.OptionName == "Url").FirstOrDefault().Value;//"http://122.155.197.149:9001/services?wsdl";

                    string strApplicationId = option.Where(m => m.OptionName == "DestinationAppId").FirstOrDefault().Value;
                    string strSecretCode = option.Where(m => m.OptionName == "SecretCode").FirstOrDefault().Value;// ConfigurationSettings.AppSettings["SecretCode"].ToString();
                    string strTransactionId = SiteCode + DateTime.Now.ToString("yyMMddHHmmssfffff");
                    string strReturnUrl = "";
                    string strProcess = "createAnnounce";
                    string strData = "";
                    GovernmentOffice g_office_code = context.GovernmentOffices.Where(m => m.system_code == SiteId).FirstOrDefault();

                    List<SendAnnounceItem> objItems = new List<SendAnnounceItem>();
                    foreach (var PrItemInfo in PrItemList)
                    {
                        string strUnit = PrItemInfo.MasResourceItem != null ? (PrItemInfo.MasResourceItem.MasUnit != null ? PrItemInfo.MasResourceItem.MasUnit.Name : "หน่วย") : "หน่วย";

                        SendAnnounceItem objItem = new SendAnnounceItem()
                        {
                            product_code = (PrItemInfo.MasResourceItem != null ? PrItemInfo.MasResourceItem.Code : PrItemInfo.MasBudgetExpense.Code),
                            product_name = "[" + (PrItemInfo.MasResourceItem != null ? PrItemInfo.MasResourceItem.Name : PrItemInfo.MasBudgetExpense.Name) + "] " + PrItemInfo.Descr,
                            quantity = PrItemInfo.Qty.ToString(),
                            price = PrItemInfo.Price.ToString(),
                            amount = "0",
                            unit = strUnit,
                            remark = "",
                            doc_id = g_office_code.g_office_code + ":" + PrItemInfo.PrItemId.ToString(),
                        };

                        objItems.Add(objItem);
                    }

                    PurchaseRequest PrInfo = PrItemList[0].PurchaseRequest;
                    SendAnnounce objHead = new SendAnnounce()
                    {
                        announce_code = PrInfo.Code,
                        supplier_tax_code = ContactCode,
                        supplier_branch_code = BranchName,
                        announce_date = Main.ConvertDateToStringForGateway(PrInfo.PurchaseDate),
                        g_office_code = g_office_code.g_office_code,//"0994000002041",
                        g_office_name = g_office_code.g_office_name,//"สถาบันรับรองคุณภาพสถานพยาบาล",
                        remark = PrInfo.Remark,
                        contact_code = EmpCode,
                        contact_name = EmpName,
                        project_code = "",
                        project_name = "",
                        valid_date = Main.ConvertDateToStringForGateway(PrInfo.ConfirmDate),
                        delivery_date = Main.ConvertDateToStringForGateway(PrInfo.RequireDate),
                        telephone = Tel,
                        doc_id = g_office_code.g_office_code + ":" + PrInfo.PrId.ToString(),
                        item = objItems,
                    };

                    strData = JsonConvert.SerializeObject(objHead);
                    service.RequestEncoding = Encoding.UTF8;
                    string result = service.ws_send_request(strApplicationId, strSecretCode, strTransactionId, strReturnUrl, strProcess, strData);

                    if (result.Substring(0, 2) == "\"{")
                    {
                        result = result.Substring(1, result.Length - 2);
                    }

                    if (result.Last() == '"')
                    {
                        result = result.Remove(result.Length - 1);
                    }

                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    ReturnRequest obj = jss.Deserialize<ReturnRequest>(result);
                    //lblResult.Text = obj.transaction_ref + " / " + obj.code + " / " + obj.description + " / " + obj.response_code
                    //    + " / " + obj.response_description + " / " + obj.response_success + " / " + obj.data;

                    return obj.response_code;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
                finally
                {

                }
            }
        }
    }
}
